package com.jqkb.pages;

import android.Manifest;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.fasterxml.jackson.databind.JsonNode;
import com.jqkb.R;
import com.jqkb.TheApplication;
import com.jqkb.service.NewMessageService;
import com.jqkb.service.UpdateVersionService;
import com.jqkb.service.UserService;
import com.jqkb.service.VersionService;
import com.jqkb.service.bean.Action;
import com.jqkb.service.bean.User;
import com.jqkb.service.util.BeanCallBack;
import com.jqkb.service.util.CallBack;
import com.jqkb.service.util.Converter;
import com.jqkb.service.util.SimpleApi;
import com.jqkb.utils.PermisionUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

import okhttp3.HttpUrl;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private static boolean downloading = false;

    private Button loginBtn;
    private EditText userEdt;
    private EditText passEdt;
    private int count = 0;
    private long time = 0;
    private long downloadId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        PermisionUtils.verifyStoragePermissions(this);
        loginBtn = (Button) findViewById(R.id.login_button);
        userEdt = (EditText) findViewById(R.id.userEdt);
        passEdt = (EditText) findViewById(R.id.passEdt);
        loginBtn.setOnClickListener(this);

        startService(new Intent(this, UpdateVersionService.class));

        if (TheApplication.isLogin()) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }


    }

    private void updateProgress(int progressValue, File apkFile) {
        Log.i("AAA", String.valueOf(progressValue));
        if (progressValue == 100) {
            int permission = ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permission == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "有权限", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "无权限 " + permission, Toast.LENGTH_SHORT).show();
            }
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            startActivity(intent);
        }
    }





    @Override
    public void onClick(View v) {


        switch (v.getId()) {


            case R.id.login_button:
                String userStr = userEdt.getText().toString();
                String passStr = passEdt.getText().toString();
                if (!"".equals(userStr) || !"".equals(passStr)) {


                    UserService service = SimpleApi.newInstance().create(UserService.class);
                    Call<ResponseBody> loginCall = service.login(userStr, passStr);
                    Converter.convert(User.class, loginCall, new BeanCallBack<User>() {

                        @Override
                        public void onSuccess(Object object, JsonNode data) {

                            User user = (User) object;
                            Toast.makeText(LoginActivity.this, user.getName(), Toast.LENGTH_SHORT).show();
                            SharedPreferences preferences = TheApplication.getSharedPreferences();
                            SharedPreferences.Editor edit = preferences.edit();
                            edit.putString("user", data.toString());
                            edit.commit();
                            TheApplication.setCurrentUser(user);

                            Intent serviceIntent = new Intent(LoginActivity.this, NewMessageService.class);
                            startService(serviceIntent);
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();


                        }

                        @Override
                        public void onFail(boolean success, int code, String message, JsonNode data) {
                            Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onNetworkFail(Call<ResponseBody> jsonNode) {
                        }

                        @Override
                        public void onError(Call<ResponseBody> response) {
                        }
                    });
                } else {
                    Toast.makeText(LoginActivity.this, "不能为空", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (!TheApplication.isLogin()) {
            stopService(new Intent(this, NewMessageService.class));
        }
    }

    public void changServerAction(View view) {

        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis - time < 1000) {
            count++;

        } else {
            count = 1;
        }
        time = currentTimeMillis;

        if (count >= 5) {
            count = 0;
            finish();
            startActivity(new Intent(LoginActivity.this, ChangeServerActivity.class));
        }


    }
}
